<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .item {
            float: left;
            text-align: center;
            width: 100px;
            height: 30px;
            line-height: 30px;
            margin: 20px;
            border: 1px solid skyblue;
        }
    </style>
</head>

<body>
    <div class="container">
        <h2 class="page-header">点击添加背景颜色</h2>
        <div class="item">1</div>
        <div class="item">2</div>
        <div class="item">3</div>
    </div>
</body>
<script>
    let items = document.querySelectorAll('.item');
    console.log(items);

    for (let i = 0; i < items.length; i++) {
        // items[i].addEventListener('click', function () {
        //     items[i].classList.toggle('active');
        // })
        items[i].onclick = function () {
            this.style.backgroundColor = 'red';
            // 使用let声明的变量是可以取到i,使用var声明的i会报错
            items[i].style.backgroundColor = 'red';
        }
    }

</script>

</html>